package com.chenyun.system.event;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.chenyun.common.constants.SysConstants;
import com.chenyun.common.enums.StoreTypeEnum;
import com.chenyun.store.aws.OssFactory;
import com.chenyun.store.pojo.StoreDTO;
import com.chenyun.system.model.SysConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Lonni
 * @date 2022-08-02 20:09
 */
public class SysConfigEvent extends ApplicationEvent {
    private final static Logger log = LoggerFactory.getLogger(SysConfigEvent.class);

    private SysConfig sysConfig;

    public SysConfigEvent(Object source, SysConfig config) {
        super(source);
        this.sysConfig = config;
    }

    public void updateConfig() {
        try {
            switch (this.sysConfig.getConfigKey()) {
                case SysConstants.YUN_SMS_STORE_KEY:
                    this.checkAndUpdateSms();
                    break;
                case SysConstants.YUN_FILE_STORE_KEY:
                    this.checkAndUpdateStore(SysConstants.YUN_FILE_STORE_KEY);
                    break;
                case SysConstants.LOCAL_FILE_STORE_KEY:
                    this.checkAndUpdateStore(SysConstants.LOCAL_FILE_STORE_KEY);
                  break;
                default:
                    return;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("更新文件存储配置失败:{}", ex.getMessage());
        }

    }

    private void checkAndUpdateSms() {
        String configValue = sysConfig.getConfigValue();
        if (StringUtils.isBlank(configValue)) {
            return;
        }
        JSONArray jsonArray = JSONUtil.parseArray(configValue);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            if (StringUtils.isBlank(Objects.toString(object.get("value")))) {
                continue;
            }
            JSONObject valueObject = JSONUtil.parseObj(object.get("value"));

//            SmsConfig.FileStoreEnum storeEnum= FileConfigDTO.FileStoreEnum.valueOf(object.get("type").toString());


        }


    }




    void  checkAndUpdateStore(String storeType){
       try {
           String configValue = sysConfig.getConfigValue();
           if (StringUtils.isBlank(configValue)) {
               return;
           }
           List<StoreDTO> dtos=new ArrayList<>();
           if (storeType.equals(SysConstants.LOCAL_FILE_STORE_KEY)){
               StoreDTO dto = this.checkAndUpdateLocalFileStore(configValue);
               dtos.add(dto);
           }else if (storeType.equals(SysConstants.YUN_FILE_STORE_KEY)){
               List<StoreDTO> storeDTOS = this.checkAndUpdateFileStore(configValue);
               if (CollectionUtil.isNotEmpty(storeDTOS)){
                   dtos.addAll(storeDTOS);
               }
           }
           OssFactory.init(JSON.toJSONString(dtos), sysConfig.getTenantId());

       }catch (Exception exception){
           log.error("加载文件存储失败:{}",exception.getMessage());
       }

    }

    /**
     * 检查是否是文件云存储更新
     */
    private List<StoreDTO> checkAndUpdateFileStore(String configValue ) {
        JSONArray jsonArray = JSONUtil.parseArray(configValue);
        if (jsonArray.size()==0){
            return  null;
        }
        List<StoreDTO> storeDTOS= new ArrayList<>(jsonArray.size());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            if (StringUtils.isBlank(Objects.toString(object.get("value")))) {
                continue;
            }
            JSONObject valueObject = JSONUtil.parseObj(object.get("value"));
            StoreDTO dto = StoreDTO.builder()
                    .typeEnum(StoreTypeEnum.valueOf((object.getStr("type")).toUpperCase()))
                    .enable(Boolean.valueOf(object.getStr("enable")))
                    .accessKey(valueObject.getStr("accessKey"))
                    .bucket(valueObject.getStr("buckName"))
                    .secretKey(valueObject.getStr("secretKey"))
                    .endpoint(valueObject.getStr("url"))
                    .https(valueObject.containsKey("https")?Boolean.valueOf(object.getStr("https")):false)
                    .region(valueObject.containsKey("region")?valueObject.getStr("region"):null)
                    .expireTime(valueObject.containsKey("expireTime")? valueObject.getInt("expireTime") :7 )
                    .accessPolicy(valueObject.containsKey("accessPolicy")? valueObject.getStr("accessPolicy") :"0" )
                    .build();
            storeDTOS.add(dto);

        }
        return storeDTOS;
    }

    StoreDTO checkAndUpdateLocalFileStore( String configValue) {
        log.info("查询出默认的本地文件设置,初始化操作类");
        JSONObject jsonObject = JSONUtil.parseObj(configValue);
        StoreDTO dto=StoreDTO.builder()
                .enable(Boolean.valueOf(jsonObject.getStr("enable")))
                .typeEnum(StoreTypeEnum.LOCAL)
                .domain(jsonObject.containsKey("domain")?jsonObject.getStr("domain"):"")
                .baseDir(jsonObject.containsKey("basePath")?jsonObject.getStr("basePath"):"")
                .build();
        return dto;
    }

}
